package utils;

import Q2.pojo.Student;
import lombok.NonNull;

import javax.persistence.Id;
import javax.persistence.Table;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

public class PersistenceUtils {

    /**
     * Get entity operate database table name
     *
     * @param clazz entity class
     * @return table name
     */
    public static String getTableName(@NonNull Class<?> clazz) {
        try {
            return clazz.getAnnotation(Table.class).name();
        } catch (NullPointerException e) {
            throw new RuntimeException("Not found table name on entity class.");
        }
    }

    /**
     * Get database table primary key name, @Id remark field name
     *
     * @param clazz entity class
     * @return primary key name
     */
    public static String getPrimaryKeyName(@NonNull Class<?> clazz) {
        final AtomicReference<List<String>> atomicNameList = new AtomicReference<>(new ArrayList<>());
        final Field[] fields = Student.class.getDeclaredFields();
        Arrays.stream(fields).forEach(field -> {
            if (field.getAnnotation(Id.class) != null) {
                atomicNameList.get().add(field.getName());
            }
        });

        final List<String> nameList = atomicNameList.get();
        if (nameList.size() == 0) {
            throw new RuntimeException("Not found any primary key.");
        } else if (nameList.size() > 1) {
            throw new RuntimeException("Multi primary key.");
        }

        return nameList.get(0);
    }

}
